define(['app','laydate'], function( app ) {
    'use strict';

    app.directive('datetimepicker', function ( $timeout ) {
        return{
            require: '?ngModel',
            restrict: 'A',
            link: function(scope, element, attrs, ngModel){
                var _date = null;
                // 渲染模板完成后执行
                $timeout(function(){
                    if( !attrs.id ){
                        element.attr('id', attrs.name );
                        attrs.id = attrs.name;
                    }
                    var dateattr = { event:'focus',isclear:1};
                    dateattr.elem = '#' +  attrs.id;
                    if( attrs.format )
                        dateattr.format = attrs.format;
                    if( attrs.istime )
                        dateattr.istime = true;
                    if( attrs.min )
                        dateattr.min  = attrs.min;
                    if( attrs.max )
                        dateattr.max  = attrs.max;
                    if( attrs.event )
                        dateattr.event = attrs.event;
                    dateattr.choose =  function( date){
                        scope.$apply(setViewValue);
                    };

                    _date = laydate( dateattr );

                    ngModel.$render = function() {
                        element.val(ngModel.$viewValue || '');
                    };

                    element.on('blur keyup change', function( e ) {
                        scope.$apply(setViewValue);
                    });

                    setViewValue();
                    // 更新模型上的视图值
                    function setViewValue() {
                        var val = element.val();
                        ngModel.$setViewValue(val);
                        ngModel.$render();
                    }
                },0);

            }
        };
    });
});